//
// The Tip of the Iceberg: A Quantitative Framework for Estimating Trade Costs' 
//             by Irarrazabal, Moxnes and Opromolla (2014)

// ---------------------------------------------
// Descriptives before truncating the dataset.
// ---------------------------------------------
clear all

cd /Dropbox/RnD_KK/tradecost_replication/

global datapath "data"
global tmppath "tmp"



// -------------------------------------------
// Is the |demand elasticity| falling faster among low than high price firms, as distance increases (triple interaction)
// -------------------------------------------
//log using "$savepath/logs/elasticities", replace

use "$tmppath/tmp_tc", clear

// Create instrument: Average price in other markets.
egen psum = sum(price), by(foretak impeks varenr year)    // Sum of prices across destinations per product
egen mkts = count(price), by(foretak impeks varenr year)  // Number of destinations per product
gen price_other = (psum-price)/(mkts-1)
label var price_other "Average price in other markets"
drop psum mkts

bys varenr iso2: egen p75_price = pctile(price), p(75)
bys varenr iso2: egen p25_price = pctile(price), p(25)
bys varenr iso2: egen p50_price = pctile(price), p(50)
bys varenr iso2: egen p50_price_other = pctile(price_other), p(50)

gen H_price = price > p50_price
gen H_price_other = price_other > p50_price_other
gen ln_qty = log(qty)
gen ln_price = log(price)
gen ln_price_other = log(price_other)

egen numfirms = count(foretak), by(varenr iso2)
drop if numfirms<10

gen lndist = log(dist)
gen lncgdp = log(cgdp)
gen lngdp = log(cgdp*pop)
encode iso2, gen(iso2x)

// Create firm-product ID
bys foretak varenr: gen id_firmprod = 1 if _n==1
replace id_firmprod = sum(id_firmprod)

// Create product-destination ID
bys varenr iso2: gen id_proddest = 1 if _n==1
replace id_proddest = sum(id_proddest)

global xvars "c.ln_price#c.lndist#H_price ln_price c.ln_price#c.lndist H_price c.ln_price#i.H_price c.lndist#i1.H_price"
global xvarsiv "c.ln_price_other#c.lndist#H_price_other ln_price_other c.ln_price_other#c.lndist H_price_other c.ln_price_other#i.H_price_other c.lndist#i1.H_price_other"

// Product-destination FE: TABLE 1, column labeled OLS
xtreg ln_qty $xvars, fe i(id_proddest) vce(cluster id_proddest)

// IV
gen inter = ln_price*lndist*H_price
gen inter_iv = ln_price_other*lndist*H_price_other 
gen vv1 = ln_price
gen iv_vv1 = ln_price_other
gen vv2 = ln_price*lndist
gen iv_vv2 = ln_price_other*lndist
gen vv3 = H_price
gen iv_vv3 = H_price_other
gen vv4 = ln_price*H_price
gen iv_vv4 = ln_price_other*H_price_other
gen vv5 = lndist*H_price
gen iv_vv5 = lndist*H_price_other

tsset id_proddest foretak

xtivreg ln_qty (inter vv* = inter_iv iv_vv*), fe first // : TABLE 1, column labeled IV
estimates store iv

